import { defineBuildConfig } from 'unbuild'

export default defineBuildConfig({
  entries: [
    { input: 'src/index.ts' },
    { input: 'src/pm/resource-manager.ts', outDir: 'dist/pm' },
    { input: 'src/pm/config-manager.ts', outDir: 'dist/pm' },
    { input: 'src/pm/session-config-manager.ts', outDir: 'dist/pm' },
    { input: 'src/pm/auto-session-manager.ts', outDir: 'dist/pm' },
    { input: 'src/pm/enhanced-session-manager.ts', outDir: 'dist/pm' },
    { input: 'src/pm/menu-validator.ts', outDir: 'dist/pm' },
    { input: 'src/pm/page-validator.ts', outDir: 'dist/pm' },
    { input: 'src/pm/css-framework-validator.ts', outDir: 'dist/pm' },
  ],
  clean: true,
  rollup: {
    inlineDependencies: true,
    esbuild: {
      target: 'node16',
      minify: true,
    },
  },
  hooks: {
    'build:done': async (ctx) => {
      // 复制 PM 静态资源文件到 dist 目录
      const fs = await import('fs-extra')
      const path = await import('path')

      const srcAssetsPath = path.join(ctx.options.rootDir, 'src/pm/assets')
      const srcToolsPath = path.join(ctx.options.rootDir, 'src/pm/tools')
      const distPmPath = path.join(ctx.options.outDir, 'pm')

      // 复制 assets 目录
      if (await fs.pathExists(srcAssetsPath)) {
        const distAssetsPath = path.join(distPmPath, 'assets')
        await fs.copy(srcAssetsPath, distAssetsPath, {
          overwrite: true
        })
        console.log('✅ PM assets 资源文件已复制到 dist 目录')
      }

      // 复制 tools 目录（包含 prompts、framework、script 等）
      if (await fs.pathExists(srcToolsPath)) {
        const distToolsPath = path.join(distPmPath, 'tools')
        await fs.copy(srcToolsPath, distToolsPath, {
          overwrite: true
        })
        console.log('✅ PM tools 资源文件已复制到 dist 目录')

        // 特别检查 script 目录是否复制成功
        const srcScriptPath = path.join(srcToolsPath, 'script')
        const distScriptPath = path.join(distToolsPath, 'script')
        if (await fs.pathExists(srcScriptPath) && await fs.pathExists(distScriptPath)) {
          console.log('✅ PM script 启动脚本已复制到 dist 目录')
        }
      }
    }
  }
})
